"""
认证路由
"""
from flask import request, jsonify
from flask_jwt_extended import (
    create_access_token,
    create_refresh_token,
    jwt_required,
    get_jwt_identity,
    get_jwt
)
from datetime import datetime, timedelta
from app.blueprints.auth import auth_bp
from app.models.user import User
from app.models.session import Session
from app.models.log import SystemLog
from app.extensions import db


@auth_bp.route('/register', methods=['POST'])
def register():
    """用户注册"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['username', 'password', 'role', 'first_name', 'last_name', 'college', 'department']
        for field in required_fields:
            if field not in data or not data[field]:
                return jsonify({
                    'success': False,
                    'error': f'Missing required field: {field}'
                }), 400
        
        # 禁止通过注册接口创建管理员账户
        if data['role'] == 'admin':
            return jsonify({
                'success': False,
                'error': 'Cannot register as admin. Admin accounts must be created by existing administrators.'
            }), 403
        
        # 验证角色有效性
        if data['role'] not in ['student', 'teacher']:
            return jsonify({
                'success': False,
                'error': 'Invalid role. Only student and teacher roles are allowed for registration.'
            }), 400
        
        # 检查用户名是否已存在
        if User.query.filter_by(username=data['username']).first():
            return jsonify({
                'success': False,
                'error': 'Username already exists'
            }), 400
        
        # 检查邮箱是否已存在（如果提供了邮箱）
        email = data.get('email')
        if email and User.query.filter_by(email=email).first():
            return jsonify({
                'success': False,
                'error': 'Email already exists'
            }), 400
        
        # 创建新用户
        user = User(
            username=data['username'],
            email=email if email else None,
            role=data['role'],
            first_name=data['first_name'],
            last_name=data['last_name'],
            college=data['college'],
            department=data['department'],
            phone=data.get('phone')
        )
        user.set_password(data['password'])
        
        db.session.add(user)
        db.session.flush()  # 刷新以获取user.id
        
        # 根据角色创建对应的profile
        if data['role'] == 'student':
            from app.models.user import StudentProfile
            student_profile = StudentProfile(
                user_id=user.id,
                student_id=data['username'],  # 使用学号作为student_id
                major='',  # 可以从学院/系部推断，或后续完善
                grade_level=1  # 默认为大一
            )
            db.session.add(student_profile)
        elif data['role'] == 'teacher':
            from app.models.user import TeacherProfile
            teacher_profile = TeacherProfile(
                user_id=user.id,
                employee_id=data['username'],  # 使用工号作为employee_id
                department=data['department'],
                title='讲师'  # 默认职称
            )
            db.session.add(teacher_profile)
        
        db.session.commit()
        
        # 记录日志
        log = SystemLog(
            user_id=user.id,
            action='register',
            resource_type='user',
            resource_id=str(user.id),
            ip_address=request.remote_addr,
            status='success',
            level='INFO',
            message=f'User {user.username} registered successfully with profile'
        )
        db.session.add(log)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'User registered successfully',
            'data': user.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@auth_bp.route('/login', methods=['POST'])
def login():
    """用户登录"""
    try:
        data = request.get_json()
        
        if not data or 'username' not in data or 'password' not in data:
            return jsonify({
                'success': False,
                'error': 'Missing username or password'
            }), 400
        
        # 查找用户
        user = User.query.filter_by(username=data['username']).first()
        
        if not user or not user.check_password(data['password']):
            # 记录失败日志
            log = SystemLog(
                action='login',
                resource_type='user',
                ip_address=request.remote_addr,
                status='failed',
                level='WARNING',
                message=f'Failed login attempt for username: {data["username"]}'
            )
            db.session.add(log)
            db.session.commit()
            
            return jsonify({
                'success': False,
                'error': 'Invalid username or password'
            }), 401
        
        if not user.is_active:
            return jsonify({
                'success': False,
                'error': 'Account is inactive'
            }), 401
        
        # 创建JWT令牌
        access_token = create_access_token(identity=str(user.id))
        refresh_token = create_refresh_token(identity=str(user.id))
        
        # 保存会话
        session = Session(
            user_id=user.id,
            token=access_token,
            refresh_token=refresh_token,
            ip_address=request.remote_addr,
            user_agent=request.headers.get('User-Agent'),
            expires_at=datetime.utcnow() + timedelta(hours=1)
        )
        db.session.add(session)
        
        # 记录成功日志
        log = SystemLog(
            user_id=user.id,
            action='login',
            resource_type='user',
            resource_id=str(user.id),
            ip_address=request.remote_addr,
            status='success',
            level='INFO',
            message=f'User {user.username} logged in successfully'
        )
        db.session.add(log)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Login successful',
            'data': {
                'access_token': access_token,
                'refresh_token': refresh_token,
                'user': user.to_dict()
            }
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@auth_bp.route('/refresh', methods=['POST'])
@jwt_required(refresh=True)
def refresh():
    """刷新访问令牌"""
    try:
        current_user_id = int(get_jwt_identity())
        new_access_token = create_access_token(identity=str(current_user_id))
        
        return jsonify({
            'success': True,
            'data': {
                'access_token': new_access_token
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@auth_bp.route('/logout', methods=['POST'])
@jwt_required()
def logout():
    """用户登出"""
    try:
        current_user_id = int(get_jwt_identity())
        jti = get_jwt()['jti']
        
        # 撤销当前会话
        session = Session.query.filter_by(user_id=current_user_id).first()
        if session:
            session.is_revoked = True
            db.session.commit()
        
        # 记录日志
        log = SystemLog(
            user_id=current_user_id,
            action='logout',
            resource_type='user',
            resource_id=str(current_user_id),
            ip_address=request.remote_addr,
            status='success',
            level='INFO',
            message='User logged out successfully'
        )
        db.session.add(log)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': 'Logout successful'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@auth_bp.route('/me', methods=['GET'])
@jwt_required()
def get_current_user():
    """获取当前用户信息"""
    try:
        current_user_id = int(get_jwt_identity())
        user = User.query.get(current_user_id)
        
        if not user:
            return jsonify({
                'success': False,
                'error': 'User not found'
            }), 404
        
        return jsonify({
            'success': True,
            'data': user.to_dict()
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

